package com.you.springcloudconfig.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.util.List;

/**
 * Created by Linzk on 2020/12
 */
@RestController
@RequestMapping("/client-consumer")
public class ConfigClientConsumerController {

    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private DiscoveryClient discoveryClient; // 服务发现 动态获取 eureka server 路径

    // @Value("${name}")
    // private String name; // 获取远程 Gitee 仓库中配置的属性

    @RequestMapping("/config")
    public String getConfig() {
        List<ServiceInstance> instances = discoveryClient.getInstances("config-eureka-provider"); // 获取注册中心上提供者的路径
        if (instances == null && instances.size() == 0){
            return null;
        } // 对集合进行判断
        ServiceInstance serviceInstance = instances.get(0); // 这个集合是 eureka 网页中 status 的集合，参数是其中的索引
        String host = serviceInstance.getHost();
        int port = serviceInstance.getPort();
        String url = "http://config-eureka-provider/client-provider/config";
        String name = restTemplate.getForObject(url, String.class);
        return "consumer: " + name;
    }



}
